package org.oaix.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageUrlToByte {
    public static byte[] convertImageUrlToBytes(String imageUrl) throws IOException {
        // 创建URL对象（验证URL格式）
        URL url = new URL(imageUrl);

        try (InputStream inputStream = url.openStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[4096]; // 4KB缓冲区
            int bytesRead;

            // 读取数据并写入缓存
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 返回字节数组
            return outputStream.toByteArray();
        }
    }

    // 最大重定向次数，防止无限重定向
    private static final int MAX_REDIRECTS = 5;

    public static byte[] downloadImage(String imageUrl) throws IOException {
        return downloadImageWithRedirects(imageUrl, 0);
    }

    private static byte[] downloadImageWithRedirects(String imageUrl, int redirectCount) throws IOException {
        if (redirectCount > MAX_REDIRECTS) {
            throw new IOException("重定向次数过多（超过 " + MAX_REDIRECTS + " 次）");
        }

        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求头避免被拒绝
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        connection.setRequestProperty("Accept", "image/webp,image/*,*/*;q=0.8");

        // 设置超时时间
        connection.setConnectTimeout(10000); // 10秒连接超时
        connection.setReadTimeout(30000);    // 30秒读取超时

        // 禁止自动重定向，以便手动处理
        connection.setInstanceFollowRedirects(false);

        int statusCode = connection.getResponseCode();

        // 处理重定向 (301, 302, 303, 307, 308)
        if (statusCode >= 300 && statusCode < 400) {
            String redirectUrl = connection.getHeaderField("Location");
            if (redirectUrl == null || redirectUrl.isEmpty()) {
                throw new IOException("重定向地址为空");
            }
            // 处理相对路径重定向
            if (!redirectUrl.startsWith("http")) {
                URL baseUrl = new URL(imageUrl);
                redirectUrl = new URL(baseUrl, redirectUrl).toString();
            }
            connection.disconnect();
            return downloadImageWithRedirects(redirectUrl, redirectCount + 1);
        }

        // 检查是否成功响应
        if (statusCode != HttpURLConnection.HTTP_OK) {
            connection.disconnect();
            throw new IOException("服务器返回错误: HTTP " + statusCode);
        }

        // 读取图片数据
        try (InputStream inputStream = connection.getInputStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[8192]; // 8KB 缓冲区
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            return outputStream.toByteArray();
        } finally {
            connection.disconnect();
        }
    }

    // 使用示例
    public static void main(String[] args) {
        String imageUrl = "http://114.55.75.34:85/zsaImgdev/getLink/684a476e91810b6644737438.png"; // 替换为实际URL
        imageUrl = "https://www.hangzhouyq.cn/zhonshian-image-test/330000/forever/personnelmanagement/2025/05/12%2FYP0SbhJt135361456397.png"; // 替换为实际URL
        try {
            byte[] imageBytes = downloadImage(imageUrl);
            System.out.println("图片字节数: " + imageBytes.length);
        } catch (IOException e) {
            System.err.println("转换失败: " + e.getMessage());
            e.printStackTrace();
        }
    }


}
